package xgin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

type RouterGroup struct {
	Name  string
	Group *gin.RouterGroup
}

func (group *RouterGroup) addRouterInfo(info RouteInfo) {
	r := &RouteInfo{
		Name:     info.Name,
		Path:     info.Path,
		Ext:      info.Ext,
		baseName: group.Name,
		basePath: group.Group.BasePath(),
		method:   info.method,
	}
	routeMap[r.RealPath()+"|"+strings.ToUpper(r.Method())] = r
}

func (group *RouterGroup) Handle(httpMethod string, info RouteInfo, handlers ...gin.HandlerFunc) gin.IRoutes {
	info.method = httpMethod
	group.addRouterInfo(info)
	return group.Group.Handle(httpMethod, info.Path, handlers...)
}

func (group *RouterGroup) Any(info RouteInfo, handlers ...gin.HandlerFunc) gin.IRoutes {
	methods := []string{http.MethodPut, http.MethodDelete, http.MethodGet, http.MethodPost, http.MethodHead}
	for _, v := range methods {
		rInfo := info
		rInfo.method = v
		group.addRouterInfo(rInfo)
	}

	return group.Group.Any(info.Path, handlers...)
}

func (group *RouterGroup) POST(info RouteInfo, handlers ...gin.HandlerFunc) gin.IRoutes {
	return group.Handle(http.MethodPost, info, handlers...)
}

func (group *RouterGroup) GET(info RouteInfo, handlers ...gin.HandlerFunc) gin.IRoutes {
	return group.Handle(http.MethodGet, info, handlers...)
}

// DELETE is a shortcut for router.Handle("DELETE", path, handle).
func (group *RouterGroup) DELETE(info RouteInfo, handlers ...gin.HandlerFunc) gin.IRoutes {
	return group.Handle(http.MethodDelete, info, handlers...)
}

// PATCH is a shortcut for router.Handle("PATCH", path, handle).
func (group *RouterGroup) PATCH(info RouteInfo, handlers ...gin.HandlerFunc) gin.IRoutes {
	return group.Handle(http.MethodPatch, info, handlers...)
}

// PUT is a shortcut for router.Handle("PUT", path, handle).
func (group *RouterGroup) PUT(info RouteInfo, handlers ...gin.HandlerFunc) gin.IRoutes {
	return group.Handle(http.MethodPut, info, handlers...)
}

// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).
func (group *RouterGroup) OPTIONS(info RouteInfo, handlers ...gin.HandlerFunc) gin.IRoutes {
	return group.Handle(http.MethodOptions, info, handlers...)
}

// HEAD is a shortcut for router.Handle("HEAD", path, handle).
func (group *RouterGroup) HEAD(info RouteInfo, handlers ...gin.HandlerFunc) gin.IRoutes {
	return group.Handle(http.MethodHead, info, handlers...)
}
